import {getStore, setStore} from '@/util/store'

import {getDictionary} from '@/api/system/dict'
import {flat2Map} from "@/util/util";
import {getToken} from "@/util/auth";

const dict = {
  state: {
    flowRoutes: getStore({name: 'flowRoutes'}) || {},
    dictCache: {
      mac_type: {},
      msg_type: {},
      log_type: {},
      vip_level: {},
    },
  },
  actions: {
    initDict({commit}) {
      if(!getToken()) return
      getDictionary({code: 'mac_type'}).then(res => {
        commit('setDictCache', {key:'mac_type', data: flat2Map(res.data.data) })
      })
      getDictionary({code: 'msg_type'}).then(res => {
        commit('setDictCache', {key:'msg_type', data: flat2Map(res.data.data)})
      })
      getDictionary({code: 'log_type'}).then(res => {
        commit('setDictCache', {key:'log_type', data: flat2Map(res.data.data)})
      })
      getDictionary({code: 'vip_level'}).then(res => {
        commit('setDictCache', {key:'vip_level', data: flat2Map(res.data.data)})
      })
    },
    //发送错误日志
    FlowRoutes({commit}) {
      return new Promise((resolve, reject) => {
        getDictionary({code: 'flow'}).then(res => {
          commit('SET_FLOW_ROUTES', res.data.data);
          resolve();
        }).catch(error => {
          reject(error)
        })
      })
    },
  },
  mutations: {
    setDictCache(state, {key, data}) {
      state.dictCache[key] = data
    },

    SET_FLOW_ROUTES: (state, data) => {
      state.flowRoutes = data.map(item => {
        return {
          routeKey: `${item.code}_${item.dictKey}`,
          routeValue: item.remark,
        };
      });
      setStore({name: 'flowRoutes', content: state.flowRoutes, type: 'session'})
    },
  }

};

export default dict;
